Browser Cookies in Selenium Automation Testing
Browser Cookies are small pieces of data stored by a web browser on behalf of a website. Cookies are commonly used to remember login sessions, user preferences, shopping-cart information, language settings, tracking information, and other state-related data. In Selenium Automation Testing, cookies can be accessed, created, retrieved, modified, and deleted through WebDriver.
Selenium WebDriver provides built-in cookie methods that allow automation testers to control cookies for the current browser session and current browsing context. Selenium's official documentation provides methods such as addCookie(), getCookieNamed(), getCookies(), deleteCookieNamed(), and deleteAllCookies().
1. Selenium Training at JustAcademy
Browser Cookies are an important topic in Selenium Automation Testing because many modern web applications depend on cookies for authentication, sessions, personalization, and maintaining application state.
For structured Selenium Automation Testing learning, you can explore the JustAcademy Selenium Automation Testing Course.
You can also register for a course demo through the JustAcademy Course Demo Registration.
2. What Are Browser Cookies?
A browser cookie is a small piece of information that a website stores in the user's browser. The browser sends relevant cookies back to the website when making subsequent requests.
Cookies help websites maintain information between different page requests and browser interactions.
Simple Example
Suppose a user logs into an online shopping website. After successful login, the website may store a session-related cookie in the browser. When the user moves from the home page to the profile page or shopping cart, the application can use the cookie to identify the existing session.
User Login
↓
Server Validates Credentials
↓
Cookie Created
↓
Browser Stores Cookie
↓
User Opens Another Page
↓
Cookie Sent With Request
↓
Server Recognizes Session
3. Why Are Cookies Important in Selenium?
Cookies are important in Selenium automation because web applications frequently use cookies to manage authentication and application state.
- Maintaining login sessions
- Testing authenticated pages
- Testing logout functionality
- Testing remember-me functionality
- Testing user preferences
- Testing shopping carts
- Testing session expiration
- Testing cookie-based security behavior
- Clearing browser state between test cases
- Reducing repetitive login operations during certain automation scenarios
4. Cookies and Selenium WebDriver
Selenium WebDriver provides cookie-management functionality through the browser's current browsing context. In Java, cookie operations are available through the driver.manage() interface.
driver.manage().addCookie(cookie);
driver.manage().getCookies();
driver.manage().getCookieNamed("cookieName");
driver.manage().deleteCookieNamed("cookieName");
driver.manage().deleteAllCookies();
The exact method names can vary between Selenium language bindings, but the underlying WebDriver functionality is designed for adding, reading, and deleting cookies.
5. Types of Browser Cookies
Cookies can be classified in different ways depending on their lifetime, purpose, and security configuration.
5.1 Session Cookies
Session cookies are generally associated with a browser session and are commonly used to maintain temporary application state.
5.2 Persistent Cookies
Persistent cookies have an expiration time and can remain available beyond the immediate browser session depending on their configuration.
5.3 Secure Cookies
Secure cookies are configured so that they are transmitted only over secure connections such as HTTPS.
5.4 HttpOnly Cookies
HttpOnly cookies are designed to restrict access from client-side scripts such as JavaScript. They are commonly used for security-sensitive session information.
5.5 SameSite Cookies
SameSite controls how cookies are handled in cross-site contexts. Common values include Strict and Lax. Selenium supports SameSite cookie configuration in supported bindings.
6. Important Cookie Attributes
| Attribute |
Description |
| Name |
Identifies the cookie. |
| Value |
Stores the cookie's associated value. |
| Domain |
Defines the domain for which the cookie is applicable. |
| Path |
Defines the URL path where the cookie is applicable. |
| Expiry |
Defines when a persistent cookie expires. |
| Secure |
Controls whether the cookie is transmitted through secure connections. |
| HttpOnly |
Helps prevent client-side scripts from accessing the cookie. |
| SameSite |
Controls cross-site cookie behavior. |
7. Selenium Cookie Methods
| Method |
Purpose |
| addCookie() |
Adds a cookie to the current browsing context. |
| getCookieNamed() |
Retrieves a cookie using its name. |
| getCookies() |
Retrieves all cookies visible to the current domain/context. |
| deleteCookieNamed() |
Deletes a cookie using its name. |
| deleteCookie() |
Deletes a specified cookie object. |
| deleteAllCookies() |
Deletes all cookies for the current domain/browsing context. |
8. Adding a Cookie in Selenium
The addCookie() method is used to add a cookie to the current browsing context. Selenium's documentation notes that the browser should first be on a domain where the cookie is valid.
Java Example
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AddCookieExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Cookie cookie = new Cookie("username", "Manish");
driver.manage().addCookie(cookie);
driver.quit();
}
}
Explanation
- Create the WebDriver object.
- Open the required domain.
- Create a Cookie object.
- Add the cookie using driver.manage().addCookie().
- Close the browser after the operation.
9. Reading a Specific Cookie
The getCookieNamed() method can be used to retrieve a cookie using its name. If the named cookie is not present, the Java API returns null.
driver.get("https://example.com");
Cookie cookie = new Cookie("username", "Manish");
driver.manage().addCookie(cookie);
Cookie retrievedCookie = driver.manage().getCookieNamed("username");
System.out.println(retrievedCookie.getName());
System.out.println(retrievedCookie.getValue());
Expected Output
username
Manish
10. Getting All Cookies
The getCookies() method retrieves all cookies visible to the current browsing context. Selenium's Java API returns them as a Set.
Set cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
System.out.println("Name: " + cookie.getName());
System.out.println("Value: " + cookie.getValue());
System.out.println("----------------------");
}
11. Complete Example for Reading All Cookies
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class ReadCookiesExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.manage().addCookie(new Cookie("username", "Manish"));
driver.manage().addCookie(new Cookie("role", "tester"));
Set cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
System.out.println("Cookie Name: " + cookie.getName());
System.out.println("Cookie Value: " + cookie.getValue());
}
driver.quit();
}
}
12. Deleting a Cookie by Name
The deleteCookieNamed() method deletes a cookie using its name. Selenium's Java API documents this as deleting the named cookie from the current domain.
driver.get("https://example.com");
driver.manage().addCookie(new Cookie("username", "Manish"));
driver.manage().deleteCookieNamed("username");
Verification
Cookie cookie = driver.manage().getCookieNamed("username");
if (cookie == null) {
System.out.println("Cookie deleted successfully");
}
13. Deleting a Cookie Object
Selenium Java also provides the deleteCookie() method for deleting a specified Cookie object.
Cookie cookie = new Cookie("username", "Manish");
driver.manage().addCookie(cookie);
driver.manage().deleteCookie(cookie);
14. Deleting All Cookies
The deleteAllCookies() method deletes all cookies visible to the current browsing context/current domain.
driver.get("https://example.com");
driver.manage().deleteAllCookies();
Practical Use
This is useful when a test must start with a clean browser state and should not reuse cookies from an earlier test.
15. Complete Cookie Management Example
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class CookieManagement {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Cookie userCookie = new Cookie("username", "Manish");
Cookie roleCookie = new Cookie("role", "tester");
// Add cookies
driver.manage().addCookie(userCookie);
driver.manage().addCookie(roleCookie);
// Get one cookie
Cookie cookie = driver.manage().getCookieNamed("username");
if (cookie != null) {
System.out.println("Name: " + cookie.getName());
System.out.println("Value: " + cookie.getValue());
}
// Get all cookies
Set cookies = driver.manage().getCookies();
for (Cookie currentCookie : cookies) {
System.out.println(
currentCookie.getName() + " = " +
currentCookie.getValue()
);
}
// Delete one cookie
driver.manage().deleteCookieNamed("username");
// Delete all cookies
driver.manage().deleteAllCookies();
driver.quit();
}
}
16. Cookie Domain
The domain attribute determines the domain for which a cookie is valid. When adding a cookie in Selenium, the current browser context must be appropriate for the cookie's domain. Selenium's documentation specifically notes that the driver should be on the domain where the cookie is valid before adding it.
driver.get("https://example.com");
Cookie cookie = new Cookie.Builder("username", "Manish")
.domain("example.com")
.build();
driver.manage().addCookie(cookie);
17. Cookie Path
The path attribute determines the URL path where the cookie is applicable.
Cookie cookie = new Cookie.Builder("username", "Manish")
.path("/")
.build();
driver.manage().addCookie(cookie);
18. Cookie Expiry
Persistent cookies can have an expiry time. Selenium supports cookie expiry configuration through its cookie APIs.
import java.time.Duration;
import java.util.Date;
Date expiry = new Date(
System.currentTimeMillis() + Duration.ofMinutes(30).toMillis()
);
Cookie cookie = new Cookie.Builder("username", "Manish")
.expiresOn(expiry)
.build();
driver.manage().addCookie(cookie);
19. Secure Cookies
A secure cookie is intended to be transmitted through secure HTTPS connections.
Cookie cookie = new Cookie.Builder("secureCookie", "true")
.isSecure(true)
.build();
driver.manage().addCookie(cookie);
20. HttpOnly Cookies
HttpOnly is a cookie attribute commonly used for security-sensitive information such as session identifiers. It prevents ordinary client-side JavaScript from directly accessing the cookie.
In automation testing, HttpOnly cookies can still be relevant because Selenium WebDriver interacts with cookies through the browser automation interface rather than requiring JavaScript access to the cookie.
21. SameSite Cookies
SameSite controls how cookies behave in cross-site scenarios. Selenium supports SameSite values such as Strict and Lax in supported bindings.
Cookie strictCookie = new Cookie.Builder("session", "abc123")
.sameSite("Strict")
.build();
Cookie laxCookie = new Cookie.Builder("preference", "dark")
.sameSite("Lax")
.build();
driver.manage().addCookie(strictCookie);
driver.manage().addCookie(laxCookie);
22. Browser Cookies for Login Automation
Cookies can be useful in authentication-related automation scenarios. For example, a test may authenticate through a normal login flow and then inspect the resulting session cookie.
driver.get("https://example.com/login");
// Perform login actions here
Cookie sessionCookie = driver.manage().getCookieNamed("session");
if (sessionCookie != null) {
System.out.println("Session cookie found");
}
Cookie-based authentication should be used carefully in test automation. Tests should not assume that a cookie can always replace the application's actual login process, because authentication mechanisms may depend on multiple cookies, server-side state, tokens, or other security controls.
23. Using Cookies to Maintain Test State
Cookies can help preserve state between different browser interactions within a test scenario.
driver.get("https://example.com");
driver.manage().addCookie(
new Cookie("testUser", "Manish")
);
driver.navigate().refresh();
Cookie cookie = driver.manage().getCookieNamed("testUser");
System.out.println(cookie.getValue());
24. Clearing Cookies Before a Test
When test cases must be isolated from previous browser state, cookies can be cleared before starting a test.
driver.manage().deleteAllCookies();
driver.get("https://example.com");
Test Flow
Start Test
↓
Clear Cookies
↓
Open Application
↓
Perform Test
↓
Validate Result
↓
End Test
25. Cookies and Session Management
Session management is one of the most important practical uses of cookies. A web application can use cookies to associate browser requests with an existing server-side session.
Browser
|
| Login Request
↓
Application Server
|
| Session Created
↓
Session Cookie
|
↓
Browser
|
| Subsequent Requests
↓
Application Server
|
| Session Recognized
↓
Authenticated Response
26. Cookies and Logout Testing
Cookies are useful when testing logout behavior. A logout test can verify whether the application's session state is cleared or invalidated according to the application's expected behavior.
// Login
// Perform login steps
Cookie session = driver.manage().getCookieNamed("session");
if (session != null) {
System.out.println("Session cookie exists");
}
// Perform logout
driver.manage().deleteAllCookies();
For actual application testing, the expected result should be based on the application's defined logout behavior rather than assuming that every logout operation must delete every cookie.
27. Cookies in Data-Driven Testing
Cookies can also be used as part of test setup when different test scenarios require different browser states.
| Test Scenario |
Cookie State |
| New User |
No authentication cookie |
| Logged-In User |
Valid session cookie |
| Expired Session |
Expired or invalid session information |
| Admin User |
Application-specific authenticated state |
| Logout Test |
Session state cleared according to application behavior |
28. Python Selenium Cookie Example
Selenium also provides cookie-management methods in Python.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
driver.add_cookie({
"name": "username",
"value": "Manish"
})
cookie = driver.get_cookie("username")
print(cookie)
driver.quit()
Python Selenium exposes methods including get_cookies(), add_cookie(), delete_cookie(), and delete_all_cookies().
29. Getting All Cookies in Python
cookies = driver.get_cookies()
for cookie in cookies:
print(cookie["name"])
print(cookie["value"])
30. Deleting a Cookie in Python
driver.delete_cookie("username")
Delete All Cookies
driver.delete_all_cookies()
31. JavaScript Selenium Cookie Example
const { Builder, Browser } = require("selenium-webdriver");
async function cookieExample() {
const driver = await new Builder()
.forBrowser(Browser.CHROME)
.build();
try {
await driver.get("https://example.com");
await driver.manage().addCookie({
name: "username",
value: "Manish"
});
const cookie = await driver.manage().getCookie("username");
console.log(cookie);
await driver.manage().deleteCookie("username");
} finally {
await driver.quit();
}
}
cookieExample();
Selenium's JavaScript API provides methods for adding, retrieving, and deleting cookies through driver.manage().
32. Cookie Validation
Cookie validation means verifying that the expected cookie exists and contains the expected attributes or value.
Cookie cookie = driver.manage().getCookieNamed("username");
if (cookie != null && cookie.getValue().equals("Manish")) {
System.out.println("Cookie validation passed");
} else {
System.out.println("Cookie validation failed");
}
33. Cookie Testing Checklist
- Verify whether the expected cookie is created.
- Verify the cookie name.
- Verify the cookie value where appropriate.
- Verify domain configuration where relevant.
- Verify path configuration where relevant.
- Verify expiry behavior.
- Verify Secure configuration where applicable.
- Verify HttpOnly behavior where applicable.
- Verify SameSite behavior where applicable.
- Verify cookies are removed after the expected logout or reset operation.
- Verify expired sessions are handled correctly.
- Verify browser state is isolated between tests when required.
34. Common Cookie Testing Scenarios
| Scenario |
Testing Objective |
| Login |
Verify expected authentication/session cookie behavior. |
| Logout |
Verify session state is invalidated according to requirements. |
| Remember Me |
Verify persistent authentication behavior. |
| Session Timeout |
Verify application behavior after session expiration. |
| Cookie Deletion |
Verify individual or complete cookie removal. |
| Cookie Modification |
Verify application behavior when cookie state changes. |
| Security |
Verify relevant Secure, HttpOnly, and SameSite configurations. |
| Browser Isolation |
Verify one test does not unexpectedly affect another test. |
35. Common Mistakes While Working with Cookies
Mistake 1: Adding a Cookie Before Opening the Domain
A common mistake is attempting to add a cookie before navigating to an appropriate domain.
// Avoid
driver.manage().addCookie(new Cookie("user", "Manish"));
// Better
driver.get("https://example.com");
driver.manage().addCookie(new Cookie("user", "Manish"));
The Selenium documentation specifies that the driver should first be on the domain where the cookie will be valid.
Mistake 2: Assuming One Cookie Represents the Entire Login State
Modern applications can use multiple cookies and additional server-side or token-based authentication mechanisms. Do not assume that one cookie alone represents the complete authentication state.
Mistake 3: Sharing Cookies Between Unrelated Domains
Cookies are associated with domain and path rules. A cookie intended for one domain should not automatically be treated as valid for another unrelated domain.
Mistake 4: Not Clearing Browser State
If tests depend on a clean state, leftover cookies can cause tests to behave differently depending on execution order.
Mistake 5: Hard-Coding Sensitive Cookie Values
Authentication cookies, session identifiers, and other sensitive values should not be committed to source-control repositories or exposed unnecessarily in logs.
36. Cookies and Test Isolation
Test isolation means that one test should not unintentionally influence another test.
Test Case 1
↓
Login
↓
Session Cookie Created
↓
Test Case Ends
↓
Clear Browser State
↓
Test Case 2
↓
Fresh Browser State
Clearing cookies can be one part of test isolation, although complete isolation may also require a fresh browser context, cleared local storage, cleared session storage, or other environment reset steps depending on the application.
37. Cookies vs Local Storage vs Session Storage
| Feature |
Cookies |
Local Storage |
Session Storage |
| Primary Purpose |
State, sessions, preferences, tracking |
Client-side persistent storage |
Client-side temporary page/session storage |
| Expiration |
Can have expiry |
Generally remains until cleared |
Associated with the browser page/session context |
| Sent With HTTP Requests |
Yes, according to cookie rules |
No |
No |
| Automation Use |
Session and cookie testing |
Client-side storage testing |
Temporary browser-state testing |
38. Practical Project: Cookie-Based Session Testing
Consider an application with the following flow:
Open Application
↓
Login
↓
Session Cookie Created
↓
Open Dashboard
↓
Read Session Cookie
↓
Validate Cookie
↓
Logout
↓
Verify Session State
Example Test Structure
public class CookieSessionTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
}
@Test
public void validateSessionCookie() {
driver.get("https://example.com/login");
// Perform login
Cookie sessionCookie =
driver.manage().getCookieNamed("session");
if (sessionCookie != null) {
System.out.println("Session cookie exists");
}
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
39. Cookie Automation with TestNG
Cookies can be integrated into TestNG-based Selenium frameworks for setup, validation, and cleanup operations.
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CookieTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.get("https://example.com");
}
@Test
public void cookieTest() {
driver.manage().addCookie(
new Cookie("testUser", "Manish")
);
Cookie cookie =
driver.manage().getCookieNamed("testUser");
assert cookie != null;
assert cookie.getValue().equals("Manish");
}
@AfterMethod
public void tearDown() {
driver.manage().deleteAllCookies();
driver.quit();
}
}
40. Best Practices for Browser Cookie Testing
- Navigate to the correct domain before adding cookies.
- Use meaningful cookie names in test data.
- Do not expose sensitive session cookies in reports or logs.
- Clear cookies when test isolation requires it.
- Validate cookie attributes according to the application's requirements.
- Do not assume that every application uses cookies in the same way.
- Combine cookie validation with functional application validation.
- Use a fresh browser context when stronger isolation is required.
- Avoid making tests dependent on a specific cookie implementation unless that implementation is part of the requirement being tested.
- Keep authentication data secure.
41. Browser Cookies Interview Questions
Q1. What is a browser cookie?
A browser cookie is a small piece of data stored by a website in the browser and used for purposes such as session management, preferences, and state management.
Q2. How do you add a cookie in Selenium?
In Selenium Java, use driver.manage().addCookie().
Q3. How do you get all cookies?
Use driver.manage().getCookies().
Q4. How do you get a specific cookie?
Use driver.manage().getCookieNamed("cookieName").
Q5. How do you delete a specific cookie?
Use driver.manage().deleteCookieNamed("cookieName") or delete the corresponding Cookie object.
Q6. How do you delete all cookies?
Use driver.manage().deleteAllCookies().
Q7. Why do you need to open the domain before adding a cookie?
Because the cookie must be valid for the current browsing context/domain. Selenium's documentation specifically describes navigating to the appropriate domain before adding the cookie.
Q8. What is a session cookie?
A session cookie is generally associated with the current browser session and is commonly used to maintain temporary application state.
Q9. What is an HttpOnly cookie?
It is a cookie configured so that ordinary client-side scripts cannot directly access it.
Q10. What is a Secure cookie?
A Secure cookie is intended to be transmitted over secure HTTPS connections.
Q11. What is SameSite?
SameSite is a cookie attribute that controls cookie behavior in cross-site contexts. Selenium supports values such as Strict and Lax in supported bindings.
42. Quick Revision
| Concept |
Key Point |
| Cookie |
Small browser-stored data associated with a website. |
| addCookie() |
Adds a cookie. |
| getCookieNamed() |
Gets a specific cookie. |
| getCookies() |
Gets all available cookies. |
| deleteCookieNamed() |
Deletes a cookie by name. |
| deleteCookie() |
Deletes a cookie object. |
| deleteAllCookies() |
Deletes all cookies in the current domain/browsing context. |
| Secure |
Cookie security attribute for secure transmission. |
| HttpOnly |
Restricts ordinary client-side script access. |
| SameSite |
Controls cross-site cookie behavior. |
43. Complete Browser Cookie Automation Flow
Start Selenium Test
↓
Launch Browser
↓
Open Required Domain
↓
Add / Read Cookies
↓
Validate Cookie Information
↓
Perform Application Actions
↓
Validate Application Behavior
↓
Delete Required Cookies
↓
Clear Browser State
↓
Close Browser
↓
End Test
44. Learning Outcomes
After completing this topic, learners should be able to:
- Understand what browser cookies are.
- Understand why web applications use cookies.
- Understand how cookies support session management.
- Add cookies using Selenium WebDriver.
- Retrieve a specific cookie.
- Retrieve all cookies.
- Delete individual cookies.
- Delete all cookies.
- Understand cookie attributes such as domain, path, expiry, Secure, HttpOnly, and SameSite.
- Use cookies in Selenium automation scenarios.
- Validate cookie-based application behavior.
- Use cookies for appropriate test setup and isolation.
- Understand cookie-related interview questions.
45. Recommended Selenium Training Resource
To learn Selenium Automation Testing in a structured manner, explore the JustAcademy Selenium Automation Testing Course.
For a course demo, visit the JustAcademy Course Demo Registration.
46. Final Summary
Browser Cookies are an important part of modern web applications and are frequently involved in authentication, sessions, preferences, and application state. Selenium WebDriver provides built-in functionality for managing cookies, including adding cookies, retrieving individual or all cookies, deleting specific cookies, and deleting all cookies.
For Selenium Automation Testers, understanding cookies is particularly useful when testing login sessions, logout behavior, session expiration, browser-state isolation, personalization, and security-related cookie attributes. Proper cookie handling should always be combined with the application's actual functional and security requirements.
Useful Links: